<!-- src/views/TaskPage.vue -->
<template>
    <div>
        <el-card>
            <div style="display: flex; justify-content: space-between; align-items: center">
                <h2>我的任务</h2>
                <div>
                    <el-button @click="refreshList" :loading="loading">刷新</el-button>
                </div>
            </div>

            <el-table :data="tasks" style="width: 100%" v-loading="loading">
                <el-table-column prop="id" label="Task ID" min-width="130" />
                <el-table-column prop="task_type" label="任务类型" />
                <el-table-column prop="status" label="状态">
                    <template #default="{ row }">
                        <el-tag :type="tagType(row.status)">
                            {{ row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间" min-width="100" :formatter="formatDate" />
                <el-table-column label="操作" width="200">
                    <template #default="{ row }">
                        <el-button size="small" @click="viewResult(row)" :disabled="isUnfinished(row)">查看</el-button>
                        <!-- <el-button size="small" type="danger" @click="cancelTask(row)" v-if="canCancel(row)">
                            取消
                        </el-button> -->
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination
                    background
                    :page-size="pageSize"
                    :total="total"
                    :current-page="page"
                    :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>

            <div style="margin-top: 12px; color: var(--el-color-info)">
                说明：页面仅在存在未完成任务时自动轮询，降低资源消耗。完成后可点击查看结果页面。
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts" name="TaskPage">
    import { onMounted, ref } from 'vue';
    import dayjs from "dayjs"
    // import { useTasks } from '@/composables/useTasks';
    import { get, post } from '@/axios/api';
    import { ElMessage } from 'element-plus';
    import { loadUser, useAuth } from '@/common/useAuth';
    import { useRouter } from 'vue-router';
    import { useTasks } from '@/common/taskUtils';

    const {
        tasks, loading, refreshList, gotoResult, cancelTask,
        page, pageSize, total, search,
    } = useTasks({ pageSize: 10 });

    function tagType(status:any) {
        if (!status) return "";
        if (["PENDING", "STARTED", "RUNNING"].includes(status)) return "info";
        if (["SUCCESS", "COMPLETED"].includes(status)) return "success";
        if (["FAILURE", "FAILED"].includes(status)) return "danger";
        return "";
    }

    const { user } = useAuth();
    const router = useRouter();

    const formatDate = (_: any, __: any, cellValue: string) => {
        return cellValue ? dayjs(cellValue).format("YYYY-MM-DD HH:mm:ss") : ""
    }

    // const { tasks, loading, refresh, goToResult, startPollingIfNeeded } = useTasks();
    function isUnfinished(row:any) {
        return ['PENDING', 'STARTED', 'RUNNING'].includes(row.status);
    }

    async function handleSizeChange(val: number) {
        pageSize.value = val;
        refreshList();
    }

    async function handleCurrentChange(val: number) {
        page.value = val;
        refreshList();
    }

    function viewResult(row:any) {
        if (row.task_type === 'maftools') {
            router.push({
                name:'maftools',
                params: {
                    taskid: row.id
                }   
            })
        } else if (row.task_type === 'deseq2') {
            router.push({
                name:'rnaseqtools',
                params: {
                    taskid: row.id
                }   
            })
        }

    }

    // 当页面进入时，useTasks 已经在 composable 中发起初次 fetch 并按需轮询
    onMounted(async() => {
        await loadUser(); 
        if (!user.value) {
            ElMessage.error('请先登录');
            setTimeout(() => {
                router.push({name: "login"});
            }, 1000)
        } else {
            refreshList()
        }
    });
</script>
<style lang="scss" scoped>
    .pagination {
        margin-top: 12px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
    }
</style>
